//
//  LGInPlayLrcShowList.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/4/10.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit

class LGInPlayLrcShowList: UIView {

    var tableView:UITableView?
    var lrcItems:[LrcItem]?{
        didSet {
            self.findFirstIndex()
        }
    }
    var lrcIndex = 0 {
        didSet {
            if lrcIndex != oldValue || lrcIndex == 0 {
                self.tableView?.reloadData()
                self.tableView?.scrollToRow(at: IndexPath.init(row: lrcIndex, section: 0), at: UITableViewScrollPosition.middle, animated: true)
            }
        }
    }


    /// 歌词滚动跟踪
    var currentDuration:Double? {
        didSet {
            if self.tableView?.isDragging == false {
                self.checkIndex()
            }
        }
    }


    /// 歌词下标更新
    func checkIndex () -> Void {
        var index = (self.lrcItems?.count)! - 1
        for lrcItem:LrcItem in self.lrcItems!.reversed() {
            if currentDuration! >= lrcItem.time! && ((lrcItem.content?.characters.count) != nil) {

                let lrc = lrcItem.content?.replacingOccurrences(of: " ", with: "")
                if  self.lrcIndex == index || lrc == "" {
                    break
                }
                self.lrcIndex = index
                var content = (lrcItem.content ?? "no data???")
                if  content == " " || content == "" {
                    content = "是一个无效内容"
                }
                #if DEBUG
                    print("内容:"+content+"\n长度:"+"\(String(describing: lrcItem.content?.characters.count))")
                #endif
                break
            }
            index = index - 1
        }
    }

    func findFirstIndex() -> Void {
        var index = 0
        for lrcItem:LrcItem in self.lrcItems! {
            let lrc = lrcItem.content?.replacingOccurrences(of: " ", with: "")
            if   lrc != "" {
                self.lrcIndex = index
                break
            }
            index = index + 1
        }
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configure()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure() {
        self.tableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        self.tableView?.register(LGInPlayLrcTableCell.classForCoder(), forCellReuseIdentifier: LGInPlayLrcTableCell.cellIdentifier())
        self.tableView?.backgroundColor = UIColor.clear
        self.tableView?.tableFooterView = UIView.init(frame: CGRect.zero)
        self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
//        self.tableView?.allowsSelection = false
        self.addSubview(self.tableView!)
        self.tableView?.snp.makeConstraints({ (make) in
            make.left.equalTo(SM_SIZE(20))
            make.right.equalTo(SM_SIZE(-20))
            make.top.bottom.equalTo(0)
        })
    }
}

//MARK: UITableViewDelegate && UITableViewDataSource implemention
extension LGInPlayLrcShowList: UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.lrcItems?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = LGInPlayLrcTableCell.tableCell(tableView: tableView) as! LGInPlayLrcTableCell
        cell.lrcLb?.text = self.lrcItems?[indexPath.row].content
        cell.lg_highLight = indexPath.row == self.lrcIndex
        return cell
    }
    
    //MARK: Reuse automatically cell height calculating
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: LGInPlayLrcTableCell.cellIdentifier(), configuration: { (cell) in
            let cell_ = cell as! LGInPlayLrcTableCell;
            cell_.lrcLb?.text = self.lrcItems?[indexPath.row].content
            cell_.lg_highLight = indexPath.row == self.lrcIndex
        })
    }

}

class LGInPlayLrcTableCell: BaseTableCell {
    var lrcLb:UILabel?
    var lg_highLight:Bool? {
        didSet {
            if lg_highLight == true {
                self.lrcLb?.textColor = SM_HEXCOLOR("#000000")
                self.lrcLb?.font = SM_CBFont(26)
            }else {
                self.lrcLb?.textColor = SM_HEXCOLOR("#4A4A4A")
                self.lrcLb?.font = SM_CFont(20)
            }
        }
    }

    override func configure() {
        super.configure()
        self.backgroundColor = UIColor.clear
        self.contentView.backgroundColor = UIColor.clear
        self.lrcLb = UILabel.init(frame: CGRect.zero)
        self.lrcLb?.font = SM_CFont(14)
        self.lrcLb?.numberOfLines = 0
        self.lrcLb?.textAlignment = NSTextAlignment.center
        self.contentView.addSubview(self.lrcLb!)
        self.lrcLb?.snp.makeConstraints({ (make) in
            make.edges.equalTo(self.contentView).inset(UIEdgeInsets.init(top: SM_SIZE(10), left: SM_SIZE(30), bottom: SM_SIZE(10), right: SM_SIZE(30)))
        })
    }


    override class func cellHeight() -> CGFloat {
        return 30;
    }
}
